<template>
    <div>
      <!--面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片试图区域-->
      <el-card>
        <!--提示区域-->
        <el-alert type="warning" title="添加商品信息" :closable="false" show-icon center></el-alert>
        <!--进度条区域  -0操作将字符串转换为数值-->
        <el-steps   :active="activeStep-0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!--标签页面区域-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs :tab-position="'left'"  v-model="activeStep" :before-leave="beforeLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <!--label 对应标题,prop对应校验规则-->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!--选择商品分类的级联选择框-->
              <el-cascader expand-trigger="hover"  clearable
                           v-model="addForm.goods_cat"
                           :options="cateList"
                           :props="cascadeProps" @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!--动态参数-->
            <el-form-item :label="item.attr_name" v-for="(item,i) in many_data" :key="i">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,id) in item.attr_vals" :key="id" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item,i) in only_data" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--action 表示图片要上传的地址-->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerObj"
              :onSuccess="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!--富文本编辑器组件-->
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
            />
            <el-button type="primary" @click="addGoodsBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
        </el-form>
      </el-card>
      <!--图片预览窗口-->
      <el-dialog
        title="图片预览"
        :visible.sync="prevPicDialogVisible"
        width="50%">
        <el-image :src="prevpic"></el-image>
        <span slot="footer" class="dialog-footer">
       <el-button type="primary" @click="prevPicDialogVisible = false">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>

<script>
  export default {
    name: 'Goodsadd',
    data:function () {
      return{
        activeStep:"0",
        checkList:[],
        cascadeProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
        },
        //商品分类列表
        cateList:[],
        many_data:[],  //动态参数
        only_data:[], //静态属性
        //添加商品表单项
        addForm:{
          goods_name:'',
          goods_price:0,
          goods_weight:0,
          goods_number:0,
          goods_introduce:'',
          //商品所属的分类
          goods_cat:[],
          pics:[] , //图片数组,
          attrs:[]
        },

        //表单验证规则
        addFormRules:{
          goods_name:[
            {required:true ,message:'请输入商品名称',trigger:'blur'}
          ],
          goods_price:[
            {required:true ,message:'请输入商品价格',trigger:'blur'}
          ],
          goods_weight:[
            {required:true ,message:'请输入商品重量',trigger:'blur'}
          ],
          goods_number:[
            {required:true ,message:'请输入商品数量',trigger:'blur'}
          ],
          goods_cat:[
            {required:true ,message:'请选择商品分类',trigger:'blur'}
          ],
        },
        //图片上传的请求头token对象
        headerObj:{
          Authorization: window.sessionStorage.getItem("token")
        },
        //图片预览窗口是否显示
        prevPicDialogVisible:false,
        prevpic:''

      }
    },
    created () {
      this.getCateList();
    },
    methods:{
      async getCateList(){
        var data=await this.$axios.get('categories');
        var res=data.data;
        if (res.meta.status!=200){
          return this.$message.error("获取商品分类失败");
        }
        this.cateList=res.data;
      },
      //级联选择权选择变化
      handleChange(){
        if(this.addForm.goods_cat.length<3){
          this.addForm.goods_cat=[];
        }
      },
      //标签切换前的函数
      beforeLeave(activeName,oldActiveName){
        if(oldActiveName==0 && this.addForm.goods_cat.length!==3){
          this.$message.error('请先选择商品分类!');
          return false;
        }
      },
      async tabClick(){
        console.log(this.activeStep);
        if(this.activeStep==1){
         var data= await this.$axios.get("categories/"+this.cateId+"/attributes",{params:{sel:'many'}});
         var res=data.data;
         if(res.meta.status!=200){return this.$message.error("获取动态参数失败!")}
         res.data.forEach(item=>{
           if(item.attr_vals==''){
             item.attr_vals=[];
           }else{
             item.attr_vals=item.attr_vals.split(' ');
           }
         });
          this.many_data=res.data;
        } /*静态属性面板*/
        else if(this.activeStep==2){
          var data= await this.$axios.get("categories/"+this.cateId+"/attributes",{params:{sel:'only'}});
          var res=data.data;
          if(res.meta.status!=200){return this.$message.error("获取静态属性失败!")}
/*          res.data.forEach(item=>{
            if(item.attr_vals==''){
              item.attr_vals=[];
            }else{
              item.attr_vals=item.attr_vals.split(' ');
            }
          });*/
          this.only_data=res.data;
          console.log("only_data=>",this.only_data);
        }
      },
      //图片预览
      handlePreview(file){
        this.prevpic=file.response.data.url;
        this.prevPicDialogVisible=true;

      },
      handleRemove(file){
        console.log(file.response.data.tmp_path);
        //获取临时路径
        var tmp_path=file.response.data.tmp_path;
        this.addForm.pics.forEach((item,index)=>{
          if(item.pic===tmp_path){
            this.addForm.pics.splice(index,1);
            console.log(this.addForm);
          }

        });


      },
      //监听图片上传
      handleSuccess(response){
        console.log(response);
        var picInfo={pic:
        response.data.tmp_path};
        this.addForm.pics.push(picInfo);
        console.log(this.addForm);
      },
      addGoodsBtn(){
        this.$refs.addFormRef.validate( async valid=>{
          if(!valid){
            return this.$message.error("请将表单填写完整!");
          }
          this.addForm.goods_cat=this.addForm.goods_cat.join(",");
          //动态参数
          this.many_data.forEach(item=>{
            var newInfo={
              attr_id:    item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            this.addForm.attrs.push(newInfo);
           });

          //静态参数提交
          this.only_data.forEach(item=>{
            var newInfo={ attr_id:item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(newInfo);
          });
          //发起请求，添加商品
          //商品名称必须为唯一的
          var data=await this.$axios.post('goods',this.addForm);
          var res=data.data;
          if(res.meta.status!=201){
            this.$message.error('添加商品失败！');
          }
          this.$message.success('添加商品成功');
          this.$router.push('/goods');
        });
      }
    },
    computed:{
      cateId(){
        if (this.addForm.goods_cat.length===3){
          return this.addForm.goods_cat[2];
        }
        return null;
      }
    },
  }
</script>

<style scoped lang="less">
.el-steps{
  margin: 20px;
  .el-steps_title{
    font-size: 12px;
  }
}

.el-checkbox{
  margin: 5px!important;
}

</style>
